package main

import "fmt"

/**
There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

分析:
已知两个有序数组a,b，求两者的中位数
首先考虑合并，由于a,b都是有序的，所以合并比较简单，合并后数组为m
找到m的中间位置i=len(m)/2,中位数为
如果是奇数个，float64(nums[i])
如果是偶数个,float64((nums[i]+nums[i-1]))/2

ps:中位数（Median）又称中值，统计学中的专有名词，是按顺序排列的一组数据中居于中间位置的数

*/
func main() {
	r := findMedianSortedArrays([]int{1, 3}, []int{2})
	//r := findMedianSortedArrays([]int{}, []int{2, 3})
	//r := findMedianSortedArrays([]int{1, 3}, []int{2,4})
	fmt.Println(r)
}

func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
	m := mergeArray(nums1, nums2)
	fmt.Print(m)
	count := len(m)
	i := len(m) / 2
	if count%2 == 0 {
		return float64(m[i]+m[i-1]) / 2
	} else {
		return float64(m[i])
	}
}

func mergeArray(nums1, nums2 []int) []int {
	i, j := 0, 0
	tmp := []int{}
	for i < len(nums1) && j < len(nums2) {
		if nums1[i] < nums2[j] {
			tmp = append(tmp, nums1[i])
			i++
		} else {
			tmp = append(tmp, nums2[j])
			j++
		}
	}
	tmp = append(tmp, nums1[i:]...)
	tmp = append(tmp, nums2[j:]...)
	return tmp
}
